// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()
const _ = db.command

// 云函数入口函数
// 删除重复的地址
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  while (true) {
    const res = await db.collection("delivery_addr")
      .aggregate()
      .lookup({
        from: "delivery_addr",
        localField: '_openid',
        foreignField: '_openid',
        as: 'ids'
      })
      .project({
        openid: "$_openid",
        ids: "$ids",
        count: _.aggregate.size("$ids")
      })
      .match({
        count: _.gt(1)
      })
      .end()
    if (res.list.length == 0) break

    for (const item of res.list) {
      item.ids.forEach(async (ele, index) => {
        if (index >= item.count - 1) return
        await db.collection('delivery_addr').where({
          _id: ele._id
        }).remove()
      })
    }
  }

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}